package com.github.postsanf.yinian.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.TextAppearanceSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.TimeKeyWordActivity;
import com.github.postsanf.yinian.bean.YNComment;
import com.github.postsanf.yinian.bean.YNUser;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.entity.YNCommonResponse;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.widget.MTextView;
import com.google.gson.Gson;
import com.litesuits.http.HttpConfig;
import com.litesuits.http.LiteHttp;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created by Administrator on 2016/7/15.
 */
public class CardCommentAdapter extends BaseAdapter {
    private Context mContext;
    private List<YNComment> mDatas;
    private int userid;
    private int groupid;

    public CardCommentAdapter(Context mContext, List<YNComment> mDatas, int userid, int groupid) {
        this.mDatas = mDatas;
        this.mContext = mContext;
        this.userid = userid;
        this.groupid = groupid;
    }

    public int getCount() {
        return mDatas.size() > 10 ? 10 : mDatas.size();
    }

    public Object getItem(int position) {
        return mDatas.get(position);
    }

    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from
                    (mContext).inflate(R.layout.cardcomment_item, null, false);
            holder.tv = (MTextView) convertView.findViewById(R.id.card_comment_tv);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        YNComment ynComment = mDatas.get(position);
        String CommentUserName = ynComment.getCommentUser().getUnickname();
        String CommentedUserName = ynComment.getCommentedUser().getUnickname();
        if (ynComment.getCommentedUser().getUserid() != CommonConstants.SYSTEM_ID) {
            String tx = CommentUserName + "回复" + CommentedUserName +
                    UIHelper.stringFilter(UIHelper.ToDBC(":" + " " + ynComment.getCcontent()));
            Spannable WordtoSpan = new SpannableString(tx);
            WordtoSpan.setSpan(new TextAppearanceSpan(mContext, R.style.item_comment_text_style1), 0, CommentUserName.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            WordtoSpan.setSpan(new TextAppearanceSpan(mContext, R.style.item_comment_text_style2), CommentUserName.length(), CommentUserName.length() + 2,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            WordtoSpan.setSpan(new TextAppearanceSpan(mContext, R.style.item_comment_text_style1), CommentUserName.length() + 2, CommentUserName.length() + CommentedUserName.length() + 3,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            WordtoSpan.setSpan(new TextAppearanceSpan(mContext, R.style.item_comment_text_style2), CommentUserName.length() + CommentedUserName.length() + 3, tx.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            holder.tv.setText(WordtoSpan);
        } else {
            String tx = CommentUserName + UIHelper.stringFilter(UIHelper.ToDBC(":" + " " + ynComment.getCcontent()));
            Spannable WordtoSpan = new SpannableString(tx);
            WordtoSpan.setSpan(new TextAppearanceSpan(mContext, R.style.item_comment_text_style1), 0, CommentUserName.length() + 1,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            WordtoSpan.setSpan(new TextAppearanceSpan(mContext, R.style.item_comment_text_style2), CommentUserName.length() + 1, tx.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            holder.tv.setText(WordtoSpan);
        }
        final YNUser cynuser = ynComment.getCommentUser();
        final YNComment delyncomment = ynComment;
        if (ynComment.getCommentUser().getUserid() != userid) {
            holder.tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent keywordintent = new Intent(mContext, TimeKeyWordActivity.class);
                    keywordintent.putExtra("text_content", true);
                    keywordintent.putExtra("cynuser", cynuser);
                    mContext.startActivity(keywordintent);
                }
            });
        } else {
            holder.tv.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    popDelComment(delyncomment);
                    return false;
                }
            });
        }
        return convertView;
    }

    private void popDelComment(final YNComment mCommentItem) {
        View sexView = View.inflate(mContext, R.layout.yn_comment_del, null);
        LinearLayout ll_ret = (LinearLayout) sexView.findViewById(R.id.ll_comment_ret);
        LinearLayout ll_del = (LinearLayout) sexView.findViewById(R.id.ll_comment_del);
        final AlertDialog alertDialog = new AlertDialog.Builder(mContext).show();
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.setContentView(sexView);
        WindowManager.LayoutParams layout = alertDialog.getWindow().getAttributes();
        layout.width = DisplayUtils.getScreenWidthPixels((Activity) mContext) - DisplayUtils.dp2px(mContext, 32 * 2);
        alertDialog.getWindow().setAttributes(layout);
        ll_ret.setVisibility(View.GONE);
        ll_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delComment(mCommentItem.getCid());
                alertDialog.dismiss();
            }
        });
    }


    // 删除评论
    private void delComment(final String comId) {
        if (StringUtils.isEmptyString(comId)) {
            Toast.makeText(mContext, "删除失败", Toast.LENGTH_SHORT).show();
            return;
        }
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_DEL_COMMENT, comId);
        StringRequest req = new StringRequest(mContext.getString(R.string.BASE_URL) + mContext.getString(R.string.ynDelComment)).setMethod(HttpMethods.Post).setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resDelComment = new Gson().fromJson(s, YNCommonResponse.class);
                        if (resDelComment != null && ReqUtils.isSuccess(resDelComment.getCode())) {
                            for (int i = 0; i < mDatas.size(); i++) {
                                if (comId.equals(mDatas.get(i).getCid())) {
                                    mDatas.remove(i);
                                    // 通知评论更新
                                    mContext.sendBroadcast(new Intent(ACTIONs.actionComment));
                                }
                            }
                        } else {
                            Toast.makeText(mContext, resDelComment.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        Toast.makeText(mContext, CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                    }
                });
        LiteHttp.newApacheHttpClient(new HttpConfig(mContext)).executeAsync(req);
    }

    private class ViewHolder {
        MTextView tv;
    }


}
